<template>
    <div class="registration-management">
        <!-- 搜索栏 -->
        <header class="fixed-header">
            <div class="search-bar">
                <el-input v-model="searchQuery" placeholder="输入名称" clearable @clear="handleSearch"
                    @keyup.enter="handleSearch">
                    <template #append>
                        <el-button :icon="Search" @click="handleSearch" />
                    </template>
                </el-input>
                <el-button type="primary" :icon="Plus" @click="handleAddRegistration">新增</el-button>
            </div>
        </header>

        <!-- 患者列表 -->
        <Main class="scroll-area">
            <el-table :data="filteredRegistrations" stripe style="width: 100%" @row-click="handleRowClick">
                <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label"
                    :sortable="column.sortable" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="link" :icon="Edit" @click.stop="handleEdit(scope.row)">编辑</el-button>
                        <el-button type="link" :icon="Delete" @click.stop="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </Main>


        <!-- 分页 -->
        <footer class="fixed-footer">
            <div class="pagination-wrap">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :total="totalRegistrations" layout="total, sizes, prev, pager, next, jumper"
                    @current-change="handlePageChange" />
            </div>
        </footer>

        <!-- 患者详情抽屉 -->
        <el-drawer v-model="drawerVisible" title="患者详情" size="40%">
            <div v-if="selectedRegistration">
                <h3>{{ selectedRegistration.name }} 的详细信息</h3>
                <el-descriptions :column="1" border>
                    <el-descriptions-item label="姓名">{{ selectedRegistration.name }}</el-descriptions-item>
                    <el-descriptions-item label="性别">{{ selectedRegistration.gender }}</el-descriptions-item>
                    <el-descriptions-item label="年龄">{{ selectedRegistration.age }}</el-descriptions-item>
                    <el-descriptions-item label="手机号码">{{ selectedRegistration.contactPhone }}</el-descriptions-item>
                    <el-descriptions-item label="住址">{{ selectedRegistration.address }}</el-descriptions-item>
                    <el-descriptions-item label="身份证号">{{ selectedRegistration.idNumber }}</el-descriptions-item>
                </el-descriptions>
            </div>
        </el-drawer>

        <!-- 新增/编辑患者对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑患者' : '新增患者'">
            <el-form :model="form" ref="formRef" label-width="100px">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="form.gender">
                        <el-radio label="男" />
                        <el-radio label="女" />
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input v-model="form.age" />
                    <!-- <el-date-picker v-model="form.birthDate" type="date" placeholder="选择日期" /> -->
                </el-form-item>
                <el-form-item label="手机号码" prop="contactPhone">
                    <el-input v-model="form.contactPhone" onkeypress="return /[0-9]/i.test(event.key)" maxlength="11" />
                </el-form-item>
                <el-form-item label="身份证号码" prop="address">
                    <el-input v-model="form.idNumber" />
                </el-form-item>
                <el-form-item label="住址" prop="address">
                    <el-input v-model="form.address" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router';
import { DeleteRegistration, GetRegistrations, PostRegistration, PutRegistration } from '@/api/RegistrationService';

const { t } = useI18n()

const columns = [
    { prop: 'name', label: '姓名', sortable: true },
    { prop: 'age', label: '年龄', sortable: true },
    { prop: 'contactPhone', label: '手机号码', sortable: true },
    { prop: 'idNumber', label: '身份证号码', sortable: true },
    { prop: 'gender', label: '性别', sortable: true },
    { prop: 'address', label: '住址' }
]

//初始化
const registrations = ref<any>([])
onMounted(async () => {
    registrations.value = await GetRegistrations()
})

// 搜索功能
const searchQuery = ref('')
const filteredRegistrations = computed(() => {
    return registrations.value.filter(registration =>
        registration.name.includes(searchQuery.value) ||
        registration.idNumber.includes(searchQuery.value))
})

// 分页功能
const currentPage = ref(1)
const pageSize = ref(10)
const totalRegistrations = computed(() => filteredRegistrations.value.length)

// 患者详情
const drawerVisible = ref(false)
const selectedRegistration = ref<any>(null)

// 新增/编辑患者
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = ref<any>({
    id: 0,
    name: "",
    idNumber: "",
    gender: "",
    age: null,
    contactPhone: "",
    address: "",
})
//新增
const handleAddRegistration = () => {
    form.value = {
        id: 0,
        name: "",
        idNumber: "",
        gender: "",
        age: null,
        contactPhone: "",
        address: "",
    }
    isEdit.value = false
    dialogVisible.value = true
}

// 方法
const handleSearch = () => {
    currentPage.value = 1
}

//
const handleRowClick = (registration) => {
    selectedRegistration.value = registration
    drawerVisible.value = true
}


// 修改
const handleEdit = (registration: any) => {
    // form.value = { ...registration }
    // const deleteProp = ['appointments', 'department', 'medicalRecords']
    // deleteProp.forEach(property => {
    //     delete form.value[property]
    // })
    form.value = {
        id: registration.id,
        name: registration.name,
        idNumber: registration.idNumber,
        gender: registration.gender,
        age: registration.age,
        contactPhone: registration.contactPhone,
        address: registration.address,
    }
    isEdit.value = true
    dialogVisible.value = true
}

//删除
const handleDelete = (registration) => {
    registrations.value = registrations.value.filter(p => p.id !== registration.id)
    DeleteRegistration(registration.id)
}

const formRef = ref<any>(null)

const handleSubmit = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                const index = registrations.value.findIndex(p => p.id === form.value.id)
                registrations.value[index] = { ...form.value }
                // PatchRegistrationApi(form.value.id, form.value)
                PutRegistration(form.value.id, form.value)
                console.log('编辑患者:', form.value)
            } else {
                registrations.value.push({ ...form.value, id: registrations.value.length + 1 })
                PostRegistration(form.value)
                console.log('新增患者:', form.value)
            }
            dialogVisible.value = false
        }
        else {
            console.log("表单验证失败");
        }
    })
}

const handlePageChange = (page) => {
    currentPage.value = page
}
</script>

<style scoped>
.registration-management {
    padding: 20px;
}

.search-bar {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
}

.pagination-wrap {
    margin-top: 20px;
    text-align: right;
}

.el-input__inner[type="tel"] {
    letter-spacing: 0.2em;
}

.fixed-top {
    position: sticky;
    top: 0;
}

.fixed-bottom {
    position: sticky;
    bottom: 0;
}
</style>